import { Component, EventEmitter, Output, OnInit, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ReceiptOrderService } from './receipt-order.service';
import { ToasterService } from '@abp/ng.theme.shared';
import { AuthService } from '@abp/ng.core';

@Component({
  selector: 'app-receipt-order-create',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">批量收货</h5>
        <button type="button" class="btn-close" (click)="closeModal(false)"></button>
      </div>
      <div class="modal-body">
        <form #form="ngForm" class="receipt-form">
          <div class="row g-3">
            <!-- 第一行 -->
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label required">到货通知单号</label>
                <input type="text" class="form-control" [(ngModel)]="model.noticeNo" name="noticeNo" required [readonly]="viewMode">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label required">货主</label>
                <select class="form-select" [(ngModel)]="model.shipper" name="shipper" required [disabled]="viewMode">
                  <option value="">--请选择--</option>
                  <option *ngFor="let shipper of shippers" [value]="shipper.value">
                    {{shipper.label}}
                  </option>
                </select>
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">托盘</label>
                <input type="text" class="form-control" [(ngModel)]="model.tray" name="tray" [readonly]="viewMode">
              </div>
            </div>

            <!-- 第二行 -->
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">储位</label>
                <input type="text" class="form-control" [(ngModel)]="model.storageLocation" name="storageLocation" [readonly]="viewMode">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label required">商品</label>
                <select class="form-select" [(ngModel)]="model.product" name="product" required [disabled]="viewMode">
                  <option value="">--请选择--</option>
                  <option *ngFor="let product of products" [value]="product.id">
                    {{product.productName}}
                  </option>
                </select>
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">单位</label>
                <input type="text" class="form-control" [(ngModel)]="model.unit" name="unit" [readonly]="viewMode">
              </div>
            </div>

            <!-- 第三行 -->
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">到货数量</label>
                <input type="number" class="form-control" [(ngModel)]="model.arrivalQty" name="arrivalQty" [readonly]="viewMode">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">数量</label>
                <input type="number" class="form-control" [(ngModel)]="model.qty" name="qty" [readonly]="viewMode">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">体积</label>
                <input type="number" class="form-control" [(ngModel)]="model.volume" name="volume" [readonly]="viewMode">
              </div>
            </div>

            <!-- 第四行 -->
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">重量</label>
                <input type="number" class="form-control" [(ngModel)]="model.weight" name="weight" [readonly]="viewMode">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">生产日期</label>
                <input type="date" class="form-control" [(ngModel)]="model.productionDate" name="productionDate" [readonly]="viewMode">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">批次</label>
                <input type="text" class="form-control" [(ngModel)]="model.batch" name="batch" [readonly]="viewMode">
              </div>
            </div>

            <!-- 第五行 -->
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">箱注</label>
                <input type="text" class="form-control" [(ngModel)]="model.remark" name="remark" [readonly]="viewMode">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">温度</label>
                <input type="text" class="form-control" [(ngModel)]="model.receiptTemperature" name="receiptTemperature" [readonly]="viewMode">
              </div>
            </div>
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">客户订单号</label>
                <input type="text" class="form-control" [(ngModel)]="model.customerNode" name="customerNode" [readonly]="viewMode">
              </div>
            </div>

            <!-- 第六行 -->
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">是否已上架</label>
                <select class="form-select" [(ngModel)]="model.isShelved" name="isShelved" [disabled]="viewMode">
                  <option [ngValue]="null">--请选择--</option>
                  <option [ngValue]="false">否</option>
                  <option [ngValue]="true">是</option>
                </select>
              </div>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button *ngIf="!viewMode" type="button" class="btn btn-secondary" (click)="closeModal(false)">取消</button>
        <button *ngIf="!viewMode" type="button" class="btn btn-primary" (click)="save()">保存</button>
      </div>
    </div>
  `,
  styles: [`
    :host {
      display: block;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.18);
      z-index: 1050;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .modal-content {
      width: 90vw;
      max-width: 1100px;
      margin: 30px auto;
      background: #fff;
      border-radius: 18px;
      box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
      border: none;
      overflow: hidden;
      animation: fadeIn 0.3s;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(40px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .modal-header {
      padding: 2rem 2.5rem 1.2rem 2.5rem;
      border-bottom: none;
      background: #f7f9fa;
    }

    .modal-title {
      font-size: 1.5rem;
      font-weight: 700;
      color: #222;
      letter-spacing: 1px;
    }

    .modal-body {
      padding: 2.5rem 2.5rem 1.5rem 2.5rem;
      background: #f7f9fa;
    }

    .receipt-form {
      padding: 0;
    }

    .form-group {
      margin-bottom: 0;
    }

    .form-label {
      font-weight: 500;
      margin-bottom: 0.5rem;
      color: #444;
      font-size: 1.05rem;
      letter-spacing: 0.5px;
    }

    .form-control, .form-select {
      padding: 0.6rem 1rem;
      border: 1.5px solid #e3e6ea;
      border-radius: 8px;
      background: #fafdff;
      font-size: 1.05rem;
      transition: border-color 0.18s, box-shadow 0.18s;
      box-shadow: none;
    }

    .form-control:focus, .form-select:focus {
      border-color: #6cb4ff;
      box-shadow: 0 0 0 2px rgba(108,180,255,0.15);
      background: #fff;
    }

    .form-control:hover, .form-select:hover {
      border-color: #b3d8ff;
    }

    .required::after {
      content: " *";
      color: #e74c3c;
      font-size: 1.1em;
    }

    .modal-footer {
      padding: 1.5rem 2.5rem 2rem 2.5rem;
      border-top: none;
      background: #f7f9fa;
      display: flex;
      justify-content: flex-end;
      gap: 1rem;
    }

    .btn {
      padding: 0.6rem 2.2rem;
      font-weight: 600;
      font-size: 1.08rem;
      border-radius: 8px;
      border: none;
      transition: background 0.18s, box-shadow 0.18s;
      box-shadow: 0 2px 8px 0 rgba(108,180,255,0.08);
    }

    .btn-primary {
      background: linear-gradient(90deg, #6cb4ff 0%, #409eff 100%);
      color: #fff;
    }
    .btn-primary:hover {
      background: linear-gradient(90deg, #409eff 0%, #6cb4ff 100%);
      color: #fff;
    }
    .btn-secondary {
      background: #e3e6ea;
      color: #444;
    }
    .btn-secondary:hover {
      background: #d1d8de;
      color: #222;
    }

    .row {
      margin: -10px;
    }
    .col-md-4 {
      padding: 10px;
    }

    /* 滚动条美化 */
    .modal-body::-webkit-scrollbar {
      width: 8px;
    }
    .modal-body::-webkit-scrollbar-thumb {
      background: #e3e6ea;
      border-radius: 8px;
    }

    /* 只读/禁用美化 */
    :host ::ng-deep input[readonly], 
    :host ::ng-deep select[disabled], 
    :host ::ng-deep textarea[readonly] {
      background: #f5f6fa !important;
      color: #888 !important;
      border-color: #e3e6ea !important;
      cursor: not-allowed;
      box-shadow: none !important;
      opacity: 1 !important;
    }
    :host ::ng-deep input[readonly]:focus, 
    :host ::ng-deep select[disabled]:focus, 
    :host ::ng-deep textarea[readonly]:focus {
      outline: none;
      box-shadow: none;
    }
  `]
})
export class ReceiptOrderCreateComponent implements OnInit {
  @Output() modalClosed = new EventEmitter<boolean>();
  @Input() editMode = false;
  @Input() editModel: any = null;
  @Input() viewMode = false;

  // 货主选项列表
  shippers = [
    { value: 'HZ001', label: '001-胡适业001' },
    { value: 'HZ002', label: '002-京东物流' },
    { value: 'HZ003', label: '003-顺丰速运' },
    { value: 'HZ004', label: '004-阿里物流' },
    { value: 'HZ005', label: '005-菜鸟物流' },
    { value: 'HZ006', label: '006-德邦快递' },
    { value: 'HZ007', label: '007-圆通速递' },
    { value: 'HZ008', label: '008-中通快递' },
    { value: 'HZ009', label: '009-韵达快递' },
    { value: 'HZ010', label: '010-申通快递' }
  ];

  // 商品列表
  products: any[] = [];

  model: any = {
    noticeNo: '',           // 到货通知单号
    customerNode: '',       // 客户订单号
    shipper: '',           // 货主
    isShelved: null,       // 是否已上架
    tray: '',              // 托盘
    storageLocation: '',    // 储位
    product: '',           // 商品
    unit: '',              // 单位
    arrivalQty: null,      // 到货数量
    qty: null,             // 数量
    volume: null,          // 体积
    weight: null,          // 重量
    productionDate: null,   // 生产日期
    batch: '',           // 批次
    remark: '',           // 箱注
    receiptTemperature: '',// 温度
    receiver: '',          // 验收人
  };

  constructor(
    private receiptOrderService: ReceiptOrderService,
    private toaster: ToasterService,
    private authService: AuthService
  ) {}

  ngOnInit() {
    this.loadProducts();
    if ((this.editMode || this.viewMode) && this.editModel) {
      // 反填表单
      this.model = { ...this.editModel };
      // 生产日期格式化，确保 input type=date 能正确显示
      if (this.model.productionDate) {
        this.model.productionDate = this.model.productionDate.substring(0, 10);
      }
    }
  }

  loadProducts() {
    this.receiptOrderService.getProductList().subscribe({
      next: (response) => {
        console.log('Products response:', response); // 添加日志
        if (response && Array.isArray(response.items)) {
          this.products = response.items;
        } else {
          console.warn('Unexpected products response format:', response);
          this.products = [];
        }
      },
      error: (error) => {
        console.error('Failed to load products:', error);
        this.products = [];
      }
    });
  }

  closeModal(result: boolean) {
    this.modalClosed.emit(result);
  }

  save() {
    if (!this.model.noticeNo) {
      this.toaster.error('到货通知单号不能为空');
      return;
    }
    if (!this.model.shipper) {
      this.toaster.error('货主不能为空');
      return;
    }
    if (!this.model.product) {
      this.toaster.error('商品不能为空');
      return;
    }
    // 自动从token获取当前登录人
    const token = localStorage.getItem('access_token');
    let receiver = '';
    if (token) {
      try {
        const payload = JSON.parse(atob(token.split('.')[1]));
        receiver = payload.preferred_username || payload.unique_name || payload.email || '';
      } catch (e) {
        console.warn('token解析失败', e);
      }
    }
    this.model.receiver = receiver;
    if (this.editMode && this.model.id) {
      // 编辑模式，调用update
      this.receiptOrderService.update(this.model.id, this.model).subscribe(() => {
        this.closeModal(true);
      });
    } else {
      // 新增
      this.receiptOrderService.create(this.model).subscribe(() => {
        this.closeModal(true);
      });
    }
  }
} 